package com.example.shop_2305.search

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.lib_base.mvvm.BaseActivity
import com.example.shop_2305.R
import com.example.shop_2305.adapter.CateOneAdapter
import com.example.shop_2305.adapter.CateTwoAdapter
import com.example.shop_2305.databinding.ActivityCateBinding
import com.example.shop_2305.fg.CategoryViewModel

@Route(path = "/app/CateActivity")
class CateActivity : BaseActivity<ActivityCateBinding,CategoryViewModel>() {
    lateinit var cateOneAdapter: CateOneAdapter
    lateinit var cateTwoAdapter: CateTwoAdapter
    override fun initView() {
        cateOneAdapter = CateOneAdapter()
        binding.rvCateone.adapter = cateOneAdapter
        binding.rvCateone.layoutManager = LinearLayoutManager(this)

        cateTwoAdapter = CateTwoAdapter()
        binding.rvCatetwo.adapter = cateTwoAdapter
        val linearLayoutManager = LinearLayoutManager(this)
        binding.rvCatetwo.layoutManager = linearLayoutManager

        viewModel.category()
        //点击左侧分类，右侧分类名称一致的进行置顶
        cateOneAdapter.setOnItemClickListener { adapter, view, position ->
            cateOneAdapter.setId(cateOneAdapter.data[position].id)
            linearLayoutManager.scrollToPositionWithOffset(position,0)
        }
        //滑动右侧，当两边显示的不一致时，修改一致的
        binding.rvCatetwo.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            //找到第一个显示的
            val position = linearLayoutManager.findFirstVisibleItemPosition()
            if(cateTwoAdapter.data[position].id!=cateOneAdapter.selectId){
                cateOneAdapter.setId(cateTwoAdapter.data[position].id)
            }
        }
    }

    override fun initData() {
       viewModel.categorySuccess.observe(this){
           if(it.code==200){
               cateOneAdapter.data.clear()
               cateOneAdapter.data.addAll(it.data)
               cateOneAdapter.notifyDataSetChanged()


               cateTwoAdapter.data.clear()
               cateTwoAdapter.data.addAll(it.data)
               cateTwoAdapter.notifyDataSetChanged()
           }
       }
    }

    override fun getViewModel(): Class<CategoryViewModel> = CategoryViewModel::class.java

    override fun getLayout(): Int  = R.layout.activity_cate

}